package tsli.acm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import tsli.acm.biz.AgentDebtManagement;
import tsli.acm.dao.GAAgentStructureDAO;
import tsli.acm.dao.GACommissionNegativeDAO;
import tsli.acm.dao.GACommissionPositiveDAO;
import tsli.acm.dao.TempAlBonusDetailDAO;
import tsli.acm.database.Database;

/**
 * Servlet implementation class ACM11022Srvl
 */
@WebServlet("/ACM11022Srvl")
public class ACM11022Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ACM11022Srvl() {
        super();
    }
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/JSON");
        Database db = new Database();
		String vaPeNo = request.getParameter("peNo");
	    String vaYearMonth = request.getParameter("monthYear");
	    String vaProcessType = request.getParameter("process_type");
	    
	   
	    if(vaProcessType==null){
	    	 GACommissionNegativeDAO  voCommissionNegativeDAO = new GACommissionNegativeDAO(db);
	     	List<Map<String, Object>> voResult = voCommissionNegativeDAO.getFreeLookDetails(vaPeNo, vaYearMonth);
	     	String[] vaPeNO = null, vaRiderCD = null , vaTotal = null, vaIssue=null,vaPoNo=null;
	     	
	     	if(voResult==null){
	     		db.close();
	     	}
	     	else{

	     		vaPeNO = new String[voResult.size()]; 
	     		vaPoNo = new String[voResult.size()]; 
	     		vaRiderCD = new String[voResult.size()];
	     		vaTotal = new String[voResult.size()];
	     		vaIssue = new String[voResult.size()];
	     		for (int i = 0; i < voResult.size(); i++) {
	     			Map<String, Object> voObject = voResult.get(i);	
	     			vaPeNO[i] = (String) voObject.get("PE_NO_COL"); 
	     			vaPoNo[i] = (String) voObject.get("PO_NO"); 
	     			vaRiderCD[i] = (String) voObject.get("RIDER_CD");	
	     			vaTotal[i] = formatMoney(voObject.get("TOTAL_FREELOOK").toString());
	     			vaIssue[i]   = (String) voObject.get("ISSUE_DATE").toString();
	     		}
	     		JSONObject voObject = new JSONObject();
	     		JSONArray voList = new JSONArray();
	     		PrintWriter voOut = response.getWriter();
	     		if (vaPeNO != null) {
	     			for (int i = 0; i < vaPeNO.length; i ++) {
	     				voList.add(vaPeNO[i]);
	     			}
	     		}
	     		voObject.put("PeNo", voList);
	     		
	     		JSONArray voList2 = new JSONArray();
	     		if (vaRiderCD != null) {
	     			for (int i = 0; i < vaRiderCD.length; i ++) {
	     				voList2.add(vaRiderCD[i]);
	     			}
	     		}
	     		voObject.put("rider",voList2);
	     		
	     		JSONArray voList3 = new JSONArray();
	     		if (vaTotal != null) {
	     			for (int i = 0; i < vaTotal.length; i ++) {
	     				voList3.add(vaTotal[i]);
	     			}
	     		}
	     		voObject.put("total",voList3);
	     		
	     		JSONArray voList4 = new JSONArray();
//	     		double sum = 0.0;
	     		if (vaIssue != null) {
	     			for (int i = 0; i < vaIssue.length; i ++) {
	     				voList4.add(vaIssue[i]);
//	     				sum += Double.parseDouble(vaIssue[i]);
	     				
	     			}
	     		}
	     		voObject.put("issue",voList4);
	     		
	     		JSONArray voList5 = new JSONArray();
	     		if (vaPoNo != null) {
	     			for (int i = 0; i < vaPoNo.length; i ++) {
	     				voList5.add(vaPoNo[i]);
	     				
	     			}
	     		}
	     		voObject.put("PoNo",voList5);
	     		
	     		
	     		voOut.print(voObject.toJSONString());
	     		db.close();
	     		
	     	}
	    }else{
	    	
	    	GACommissionPositiveDAO vocommissionPositiveDAO = new GACommissionPositiveDAO(db);
		    List<Map<String, Object>> voResult = vocommissionPositiveDAO.getActiveAgAndAlList(vaPeNo, vaYearMonth);
	    	String[] vaPeNO = null, vaClosYM = null , vaPoNo = null, vaPayment=null,vaAmount=null;
	    	//System.out.println("    test"+vaPeNo+"   "+vaYearMonth);
	    	vaPeNO = new String[voResult.size()]; 
	    	vaClosYM = new String[voResult.size()];
	    	vaPoNo = new String[voResult.size()];
	    	vaPayment = new String[voResult.size()];
	    	vaAmount = new String[voResult.size()];
	    	for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);	
				vaPeNO[i] = (String) voObject.get("PE_NO_COL"); 
				vaClosYM[i] = (String) voObject.get("CLOS_YM");	
				vaPoNo[i] = (String) voObject.get("PO_NO").toString();
				vaPayment[i]   = (String) voObject.get("PAYMENT_MODE").toString();
				vaAmount[i]   = (String) voObject.get("AMOUNT").toString();
			}
	    	JSONObject voObject = new JSONObject();
			JSONArray voList = new JSONArray();
			PrintWriter voOut = response.getWriter();
			if (vaPeNO != null) {
				for (int i = 0; i < vaPeNO.length; i ++) {
					voList.add(vaPeNO[i]);
				}
			}
			voObject.put("PeNo", voList);
			
			JSONArray voList2 = new JSONArray();
			if (vaClosYM != null) {
				for (int i = 0; i < vaClosYM.length; i ++) {
					voList2.add(vaClosYM[i]);
				}
			}
			voObject.put("closym",voList2);
			
			JSONArray voList3 = new JSONArray();
			if (vaPoNo != null) {
				for (int i = 0; i < vaPoNo.length; i ++) {
					voList3.add(vaPoNo[i]);
				}
			}
			voObject.put("pono",voList3);
			
			JSONArray voList4 = new JSONArray();
			if (vaPayment != null) {
				for (int i = 0; i < vaPayment.length; i ++) {
					voList4.add(vaPayment[i]);
				}
			}
			voObject.put("payment",voList4);
			
			JSONArray voList5 = new JSONArray();
			if (vaAmount != null) {
				for (int i = 0; i < vaAmount.length; i ++) {
					voList5.add(vaAmount[i]);
				}
			}
			voObject.put("amount",voList5);
			voOut.print(voObject.toJSONString());
			db.close();
			
			//System.out.println(voObject.toJSONString());
	    }
	    
	    
	   
    	
    	
    	
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/JSON");
		Database db = new Database();
		String vaPeNo = request.getParameter("PeNo");
    	String vaMonth = request.getParameter("Month");
		String vaYear = request.getParameter("Year");
		
		//System.out.println("PeNo  "+vaPeNo+"    "+vaYear +"     "+vaMonth);
		TempAlBonusDetailDAO alBonusDetailDAO = new TempAlBonusDetailDAO(new Database());
		ALComponentAPIMethod alc = new ALComponentAPIMethod();
		AgentDebtManagement am = new AgentDebtManagement();
		double[] a = new double[1];
		Map<String,Object> result = alBonusDetailDAO.getBonusDetailOfPeNoSm(vaPeNo, vaYear+vaMonth);
		
		//Cape Step
		String vaOldActive = result.get("OLD_ACTIVE_AMOUNT").toString();
		String vaNewActive = result.get("NEW_ACTIVE_AMOUNT").toString();
		String ov = Integer.toString((int)(alc.percentOV(Integer.parseInt(vaOldActive))*100));
		String extraOv = Integer.toString(Integer.parseInt(ov)-14);
		String pcAl = ""+result.get("PC_OLD");
		String bonusNet = ""+result.get("BONUS_NET");
		String difBonusNetBonusFl = ""+result.get("DIF_BONUS_NET_BONUS_FL");
		String totalBonus = ""+result.get("TOTAL_BONUS");
		String vaName = ""+result.get("NAME");
		//Pipe Step 
		a[0] = Double.parseDouble(totalBonus);
		String[] result2 = am.CalAgentDebt(vaPeNo,a, db);
			
		String bonusDebt = result2[0];
		String difBonus2 = Double.toString(Double.parseDouble(totalBonus)-Double.parseDouble(bonusDebt));;
		
		String text = result2[1];
		if(text == ""||text.equals("")){
			text = "ไม่พบหนี้สิน";
		}
		
		request.setAttribute("vaOldActive", vaOldActive);
		request.setAttribute("ov", ov);
		request.setAttribute("extraOv", extraOv);
		request.setAttribute("pcAl", formatMoney(pcAl));
		request.setAttribute("bonusNet", formatMoney(bonusNet));
		request.setAttribute("difBonusNetBonusFl", formatMoney( difBonusNetBonusFl));
		request.setAttribute("totalBonus",  formatMoney(totalBonus));
		request.setAttribute("bonusDebt",  formatMoney(bonusDebt));
		request.setAttribute("difBonus2",  formatMoney(difBonus2));
		request.setAttribute("text", text);
		request.setAttribute("peno",vaPeNo);
		request.setAttribute("yymm",vaMonth+"/"+vaYear);
		request.setAttribute("YyMm",vaYear+vaMonth);
		request.setAttribute("name",vaName );
		request.setAttribute("vaNewActive", vaNewActive);
		db.close();
		RequestDispatcher voRequestDispatcher = request.getRequestDispatcher("ACM11022.jsp");
		voRequestDispatcher.forward(request, response);
		 
		
	}
	
	public String formatMoney(String money){
		double formatDouble = 0;
		NumberFormat formatter = new DecimalFormat("###,###,##0.00"); 
		try{
			formatDouble = Double.parseDouble(money);
		}catch(Exception e){
			System.out.println(e);
			return "0.00";
		}
		return formatter.format(formatDouble);
	}
	

}
